import { signal, computed, effect, batch } from "@preact/signals";

const key = "lemon_daisy_notes";
const stor = globalThis.localStorage;

const noteLoaded = signal(false);
export const reset = signal(0);
export const notes = signal([""]);
export const length = computed(() => notes.value.length);

effect(() => {
  if (noteLoaded.value) {
    stor[key] = JSON.stringify(notes.value);
  }
});

export function initNotes() {
  if (stor[key]?.startsWith("[")) {
    const data = JSON.parse(stor[key]);
    notes.value = [...data];
  }
  noteLoaded.value = true;
}

export function exportNotes() {
  return notes.value.join("\n\n");
}

export function resetNotes() {
  batch(() => {
    notes.value = [""];
    reset.value++;
  });
}

export function clearNotes() {
  delete stor[key];
}

export function importNotes(data, merge) {
  if (data.length > 1 || data[0] !== "") {
    let result = data;
    const current = structuredClone(notes.value);
    if (merge) {
      result = [...current, ...data];
    }
    batch(() => {
      notes.value = result;
      reset.value++;
    });
  }
}
